﻿using Quartz.Api.Model;
using Quartz.Api.Severs;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.Api.Helper
{
    /// <summary>
    /// Job类，用于创建定时任务
    /// </summary>
    public class HttpResultfulJob : IJob
    {
        //通过_httpClientFactory发送请求
        private readonly IHttpClientFactory _httpClientFactory;

        public HttpResultfulJob(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }
        public async Task Execute(IJobExecutionContext context)
        {
            DateTime dateTime = DateTime.Now;
            TaskOptions taskOptions = context.GetTaskOptions();
            string httpMessage = "";
            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            if (taskOptions == null)
            {
                SugarContext sugarContext = new SugarContext();
                var appinfo = new AppLog { AppInfo = $"{trigger.Name}未到找作业或可能被移除", RecordDate = DateTime.Now };
                sugarContext.Db.Insertable(appinfo).ExecuteCommand();
                return;
            }
            Console.WriteLine($"作业[{taskOptions.TaskName}]开始:{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}");
            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                SugarContext sugarContext = new SugarContext();
                var appinfo = new AppLog { AppInfo = $"{trigger.Name}未配置url", RecordDate = DateTime.Now };
                sugarContext.Db.Insertable(appinfo).ExecuteCommand();
                return;
            }

            try
            {
                Dictionary<string, string> header = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(taskOptions.AuthKey)
                    && !string.IsNullOrEmpty(taskOptions.AuthValue))
                {
                    header.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
                }
                //发送请求(获取请求响应结果)
                httpMessage = await _httpClientFactory.HttpSendAsync(
                    taskOptions.RequestType?.ToLower() == "get" ? HttpMethod.Get : HttpMethod.Post,
                    taskOptions.ApiUrl,
                    header);
            }
            catch (Exception ex)
            {
                httpMessage = ex.Message;
            }

            try
            {
                SugarContext sugarContext = new SugarContext();
                var appinfo = new TaskRecord { GroupName = taskOptions.GroupName, TaskName = taskOptions.TaskName, BeginDate = dateTime, EndDate = DateTime.Now, Msg = (string.IsNullOrEmpty(httpMessage) ? "OK" : httpMessage) };
                sugarContext.Db.Insertable(appinfo).ExecuteCommand();
            }
            catch (Exception ex)
            {
                SugarContext sugarContext = new SugarContext();
                var appinfo = new AppLog { AppInfo = $"错误信息：{ex.Message}", RecordDate = DateTime.Now };
                sugarContext.Db.Insertable(appinfo).ExecuteCommand();
            }
            Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            return;
        }



    }
}
